package com.mm.cloth.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.google.gson.Gson;
import com.mm.cloth.api.ApiClient;
import com.mm.cloth.model.WatermarkRemovalResponse;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WatermarkRemovalAPI {
    
    private static final String TAG = "WatermarkRemovalAPI";
    private static final String UPLOAD_ENDPOINT = "/api/rb/create?type=1";
    private static final String STRATEGY_ID = "4";
    
    // 使用 ApiClient 的 OkHttpClient 实例，这样就会自动包含 AuthInterceptor
    private static OkHttpClient getClient() {
        return ApiClient.getInstance().getOkHttpClient();
    }
    
    private static Gson gson = new Gson();
    
    public interface WatermarkRemovalCallback {
        void onSuccess(Bitmap resultBitmap);
        void onError(String errorMessage);
        void onProgress(String progressMessage);
    }
    
    /**
     * 上传带有遮罩的图片进行去水印处理
     * @param maskedBitmap 用户编辑后的带有遮罩的图片
     * @param callback 回调接口
     */
    public static void removeWatermark(Bitmap maskedBitmap, WatermarkRemovalCallback callback) {
        Log.d(TAG, "=== 开始去水印API调用 ===");

        if (maskedBitmap == null) {
            Log.e(TAG, "错误：输入的图片为空");
            callback.onError("图片不能为空");
            return;
        }

        Log.d(TAG, "输入图片信息：宽度=" + maskedBitmap.getWidth() + ", 高度=" + maskedBitmap.getHeight());

        try {
            // 将Bitmap转换为临时文件
            Log.d(TAG, "开始将Bitmap转换为临时文件...");
            File tempFile = bitmapToTempFile(maskedBitmap);
            if (tempFile == null) {
                Log.e(TAG, "错误：Bitmap转换为文件失败");
                callback.onError("图片处理失败");
                return;
            }

            Log.d(TAG, "临时文件创建成功：" + tempFile.getAbsolutePath());
            Log.d(TAG, "文件大小：" + tempFile.length() + " bytes");

            callback.onProgress("正在上传图片...");

            // 创建multipart请求体
            Log.d(TAG, "开始构建multipart请求体...");
            RequestBody fileBody = RequestBody.create(
                    MediaType.parse("image/png"),
                    tempFile
            );

            RequestBody strategyBody = RequestBody.create(
                    MediaType.parse("text/plain"),
                    STRATEGY_ID
            );

            MultipartBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("maskFile", "watermark_mask.png", fileBody)
                    .addFormDataPart("strategy_id", STRATEGY_ID)
                    .build();

            Log.d(TAG, "multipart请求体构建完成");

            // 创建请求 - 不需要手动添加 Authorization 头，AuthInterceptor 会自动添加
            String fullUrl = ApiClient.BASE_URL + UPLOAD_ENDPOINT;
            Request request = new Request.Builder()
                    .url(fullUrl)
                    .post(requestBody)
                    .build();
            
            // 使用 ApiClient 的 OkHttpClient 实例
            getClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    long endTime = System.currentTimeMillis();
                    Log.e(TAG, "=== 网络请求失败 ===");
                    Log.e(TAG, "失败原因：" + e.getClass().getSimpleName() + " - " + e.getMessage());
                    Log.e(TAG, "请求URL：" + request.url());

                    callback.onError("网络请求失败: " + e.getMessage());

                    // 清理临时文件
                    if (tempFile.exists()) {
                        boolean deleted = tempFile.delete();
                        Log.d(TAG, "临时文件清理：" + (deleted ? "成功" : "失败"));
                    }
                }
                
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    long endTime = System.currentTimeMillis();
                    Log.d(TAG, "=== 收到服务器响应 ===");
                    Log.d(TAG, "响应状态码：" + response.code());
                    Log.d(TAG, "响应消息：" + response.message());

                    // 打印响应头信息
                    Log.d(TAG, "响应头信息：");
                    for (String headerName : response.headers().names()) {
                        Log.d(TAG, "  " + headerName + ": " + response.header(headerName));
                    }

                    try {
                        if (response.isSuccessful()) {
                            Log.d(TAG, "请求成功，开始处理响应数据...");
                            callback.onProgress("正在解析响应...");

                            // 获取响应体大小
                            long contentLength = response.body().contentLength();
                            Log.d(TAG, "响应体大小：" + (contentLength > 0 ? contentLength + " bytes" : "未知"));

                            // 获取响应的JSON数据
                            Log.d(TAG, "开始解析JSON响应数据...");
                            String responseBody = response.body().string();
                            Log.d(TAG, "响应JSON：" + responseBody);

                            // 解析JSON响应
                            WatermarkRemovalResponse apiResponse = gson.fromJson(responseBody, WatermarkRemovalResponse.class);

                            if (apiResponse != null && apiResponse.isStatus()) {
                                Log.d(TAG, "JSON解析成功：");
                                Log.d(TAG, "  状态：" + apiResponse.isStatus());
                                Log.d(TAG, "  消息：" + apiResponse.getMessage());

                                if (apiResponse.getData() != null && apiResponse.getData().getLinks() != null) {
                                    String imageUrl = apiResponse.getData().getLinks().getUrl();
                                    Log.d(TAG, "  图片URL：" + imageUrl);
                                    Log.d(TAG, "  文件名：" + apiResponse.getData().getName());
                                    Log.d(TAG, "  文件大小：" + apiResponse.getData().getSize() + " KB");

                                    // 下载处理后的图片
                                    callback.onProgress("正在下载处理后的图片...");
                                    downloadImage(imageUrl, callback);
                                } else {
                                    Log.e(TAG, "错误：响应数据中缺少图片URL");
                                    callback.onError("服务器响应数据格式错误：缺少图片URL");
                                }
                            } else {
                                String errorMessage = apiResponse != null ? apiResponse.getMessage() : "未知错误";
                                Log.e(TAG, "API处理失败：" + errorMessage);
                                callback.onError("服务器处理失败：" + errorMessage);
                            }
                        } else {
                            Log.e(TAG, "=== 服务器返回错误 ===");
                            String errorBody = response.body() != null ? response.body().string() : "未知错误";
                            Log.e(TAG, "错误状态码：" + response.code());
                            Log.e(TAG, "错误消息：" + response.message());
                            Log.e(TAG, "错误详情：" + errorBody);

                            callback.onError("服务器错误: " + response.code() + " - " + errorBody);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "=== 响应处理异常 ===");
                        Log.e(TAG, "异常类型：" + e.getClass().getSimpleName());
                        Log.e(TAG, "异常消息：" + e.getMessage());
                        Log.e(TAG, "异常堆栈：", e);

                        callback.onError("响应处理失败: " + e.getMessage());
                    } finally {
                        Log.d(TAG, "开始清理资源...");

                        // 关闭响应
                        response.close();
                        Log.d(TAG, "HTTP响应已关闭");

                        // 清理临时文件
                        if (tempFile.exists()) {
                            boolean deleted = tempFile.delete();
                            Log.d(TAG, "临时文件清理：" + (deleted ? "成功" : "失败"));
                            Log.d(TAG, "临时文件路径：" + tempFile.getAbsolutePath());
                        } else {
                            Log.d(TAG, "临时文件不存在，无需清理");
                        }

                        Log.d(TAG, "资源清理完成");
                    }
                }
            });

        } catch (Exception e) {
            Log.e(TAG, "去水印API调用异常", e);
            callback.onError("处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 将Bitmap转换为临时文件
     */
    private static File bitmapToTempFile(Bitmap bitmap) {
        Log.d(TAG, "开始将Bitmap转换为临时文件...");
        Log.d(TAG, "Bitmap信息：宽度=" + bitmap.getWidth() + ", 高度=" + bitmap.getHeight() + ", 格式=" + bitmap.getConfig());

        try {
            // 创建临时文件
            Log.d(TAG, "创建临时文件...");
            File tempFile = File.createTempFile("watermark_", ".png");
            Log.d(TAG, "临时文件路径：" + tempFile.getAbsolutePath());

            // 将Bitmap压缩为PNG格式并写入文件
            Log.d(TAG, "开始压缩Bitmap为PNG格式...");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            long compressStartTime = System.currentTimeMillis();
            boolean compressSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            long compressEndTime = System.currentTimeMillis();

            if (!compressSuccess) {
                Log.e(TAG, "Bitmap压缩失败");
                return null;
            }

            byte[] bitmapData = baos.toByteArray();
            Log.d(TAG, "Bitmap压缩完成：");
            Log.d(TAG, "  压缩耗时：" + (compressEndTime - compressStartTime) + "ms");
            Log.d(TAG, "  压缩后大小：" + bitmapData.length + " bytes");
            Log.d(TAG, "  压缩后大小：" + String.format("%.2f", bitmapData.length / 1024.0) + " KB");

            // 写入文件
            Log.d(TAG, "开始写入临时文件...");
            long writeStartTime = System.currentTimeMillis();

            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(bitmapData);
            fos.flush();
            fos.close();
            baos.close();

            long writeEndTime = System.currentTimeMillis();
            Log.d(TAG, "文件写入完成：");
            Log.d(TAG, "  写入耗时：" + (writeEndTime - writeStartTime) + "ms");
            Log.d(TAG, "  文件大小：" + tempFile.length() + " bytes");
            Log.d(TAG, "  文件存在：" + tempFile.exists());
            Log.d(TAG, "  文件可读：" + tempFile.canRead());

            Log.d(TAG, "Bitmap转换为临时文件成功");
            return tempFile;

        } catch (IOException e) {
            Log.e(TAG, "=== 创建临时文件失败 ===");
            Log.e(TAG, "异常类型：" + e.getClass().getSimpleName());
            Log.e(TAG, "异常消息：" + e.getMessage());
            Log.e(TAG, "异常堆栈：", e);
            return null;
        }
    }
    
    /**
     * 下载处理后的图片
     * @param imageUrl 图片URL
     * @param callback 回调接口
     */
    private static void downloadImage(String imageUrl, WatermarkRemovalCallback callback) {
        Log.d(TAG, "=== 开始下载处理后的图片 ===");
        Log.d(TAG, "图片URL：" + imageUrl);

        Request downloadRequest = new Request.Builder()
                .url(imageUrl)
                .get()
                .build();

        long downloadStartTime = System.currentTimeMillis();

        getClient().newCall(downloadRequest).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                long downloadEndTime = System.currentTimeMillis();
                Log.e(TAG, "=== 图片下载失败 ===");
                Log.e(TAG, "下载耗时：" + (downloadEndTime - downloadStartTime) + "ms");
                Log.e(TAG, "失败原因：" + e.getClass().getSimpleName() + " - " + e.getMessage());
                Log.e(TAG, "图片URL：" + imageUrl);

                callback.onError("图片下载失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                long downloadEndTime = System.currentTimeMillis();
                Log.d(TAG, "=== 图片下载响应 ===");
                Log.d(TAG, "下载耗时：" + (downloadEndTime - downloadStartTime) + "ms");
                Log.d(TAG, "响应状态码：" + response.code());

                try {
                    if (response.isSuccessful()) {
                        Log.d(TAG, "图片下载成功，开始解析...");

                        // 获取图片数据
                        InputStream inputStream = response.body().byteStream();
                        Bitmap resultBitmap = BitmapFactory.decodeStream(inputStream);

                        if (resultBitmap != null) {
                            Log.d(TAG, "图片解析成功：");
                            Log.d(TAG, "  结果图片宽度：" + resultBitmap.getWidth());
                            Log.d(TAG, "  结果图片高度：" + resultBitmap.getHeight());
                            Log.d(TAG, "  图片格式：" + resultBitmap.getConfig());
                            Log.d(TAG, "=== 去水印API调用完全成功 ===");

                            callback.onSuccess(resultBitmap);
                        } else {
                            Log.e(TAG, "错误：下载的图片解析失败");
                            callback.onError("下载的图片格式错误");
                        }
                    } else {
                        Log.e(TAG, "图片下载失败：" + response.code() + " - " + response.message());
                        callback.onError("图片下载失败: " + response.code());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "图片下载处理异常：", e);
                    callback.onError("图片下载处理失败: " + e.getMessage());
                } finally {
                    response.close();
                }
            }
        });
    }

    public static void cancelAllRequests() {
        Log.d(TAG, "=== 取消所有网络请求 ===");

        OkHttpClient client = getClient();
        int runningCallsCount = client.dispatcher().runningCallsCount();
        int queuedCallsCount = client.dispatcher().queuedCallsCount();

        Log.d(TAG, "正在执行的请求数量：" + runningCallsCount);
        Log.d(TAG, "队列中的请求数量：" + queuedCallsCount);

        if (runningCallsCount > 0 || queuedCallsCount > 0) {
            client.dispatcher().cancelAll();
            Log.d(TAG, "已取消所有网络请求");
        } else {
            Log.d(TAG, "没有需要取消的网络请求");
        }
    }
}
